<template>
  <div class="divBox relative">
    <el-card class="box-card">
      <div slot="header" class="clearfix" ref="headerBox">
        <el-tabs
          v-model="tableFrom.type"
          @tab-click="getList(1)"
          v-if="checkPermi(['admin:product:tabs:headers'])"
        >
          <el-tab-pane
            :label="item.name + '(' + item.count + ')'"
            :name="item.type.toString()"
            v-for="(item, index) in headerName"
            :key="index"
          />
        </el-tabs>
        <div v-show="isShowSeach" class="container mt-1">
          <el-form inline>
            <el-form-item :label="$t('shangPinFenLei') + '：'">
              <el-cascader
                class="selWidth"
                ref="cascader"
                v-model="tableFrom.categoryId"
                @change="getList(1)"
                clearable
                filterable
                :options="adminProductClassify"
                :props="categoryProps"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item :label="$t('shangHuLeiBie') + '：'">
              <el-select
                v-model="tableFrom.isSelf"
                clearable
                :placeholder="$t('qingXuanZe')"
                class="selWidth"
                @change="getList(1)"
              >
                <el-option :label="$t('ziYing')" :value="1" />
                <el-option :label="$t('feiZiYing')" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('shangHuMingCheng') + '：'">
              <el-select
                @change="getList(1)"
                class="selWidth"
                clearable
                filterable
                v-model="tableFrom.merId"
                v-selectLoadMore="selectLoadMore"
                :loading="loading"
                remote
                :remote-method="remoteMethod"
                :placeholder="$t('qingXuanZeShangHu')"
              >
                <el-option v-for="user in merchantList" :key="user.id" :label="user.name" :value="user.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('shangPinSouSuo') + '：'">
              <el-input
                v-model="tableFrom.keywords"
                :placeholder="$t('qingShuRuShangPinMingChengGuanJianZi')"
                class="selWidth"
                clearable
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="getList(1)"
                  v-hasPermi="['admin:product:list']"
                />
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <!-- <router-link :to=" { path:'/store/list/creatProduct' } ">
          <el-button size="small" type="primary" class="mr10" v-hasPermi="['admin:product:save']">添加商品</el-button>
        </router-link> -->
        <!-- <el-button size="small" type="success" class="mr10" @click="onCopy" v-hasPermi="['admin:product:save']">商品采集</el-button> -->
        <!--<el-button size="small" icon="el-icon-upload2" @click="exports" v-hasPermi="['admin:export:excel:product']">导出</el-button>-->
        <el-button v-show="tableFrom.type=='7'" size="mini" style="margin-left: 0px" @click="batchOff">{{
          $t('piLiangQiangZhiXiaJia')
        }}</el-button>
        <el-button
          v-if="tableFrom.type === '2'"
          size="small"
          @click="batchReview"
          v-hasPermi="['platform:product:audit']"
          >{{ $t('piLiangShenHe') }}</el-button>
          <el-button type="primary" size="small" @click="exportFn">导出</el-button>
        <el-button size="small" icon="el-icon-upload2" @click="isShowSeach = !isShowSeach">{{
          $t('xianShiYinCang')
        }}</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        :highlight-current-row="true"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ fontWeight: 'bold' }"
      >
        <el-table-column key="2" type="selection" width="55" />
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item :label="$t('shangHuLeiBie') + '：'">
                <span>{{ props.row.isSelf | selfTypeFilter }}</span>
              </el-form-item>
              <el-form-item :label="$t('youFei') + '：'">
                <span>{{ props.row.postage }}</span>
              </el-form-item>
              <el-form-item :label="$t('xuNiXiaoLiang') + '：'">
                <span>{{ props.row.ficti }}</span>
              </el-form-item>

              <el-form-item :label="$t('juJueYuanYin') + '：'">
                <span>{{ props.row.reason }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" min-width="50" v-if="checkedCities.includes('ID')" />
        <el-table-column :label="$t('shangPinTuPian')" min-width="80" v-if="checkedCities.includes('shangPinTuPian')">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 36px; height: 36px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('shangPinMingCheng')"
          prop="storeName"
          min-width="180"
          v-if="checkedCities.includes('shangPinMingCheng')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('shangPinFenLei')"
          :label="$t('shangPinFenLei')"
          prop="categoryId"
          align="center"
          min-width="140"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-tag class="tag">
              {{ scope.row.categoryName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('shangPinShouJia')"
          prop="price"
          min-width="100"
          v-if="checkedCities.includes('shangPinShouJia')"
        >
        </el-table-column>
        <el-table-column
          label="商品Halyk售价"
          prop="salePrice"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="merName"
          :label="$t('shangHuMingCheng')"
          v-if="checkedCities.includes('shangHuMingCheng')"
          min-width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column :label="$t('shangHuLeiBie')" min-width="100" v-if="checkedCities.includes('shangHuLeiBie')">
          <template slot-scope="scope">
            <span>{{ scope.row.isSelf | selfTypeFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="sales"
          :label="$t('xiaoLiang')"
          v-if="checkedCities.includes('xiaoLiang')"
          min-width="100"
        />
        <el-table-column prop="stock" :label="$t('kuCun')" min-width="70" v-if="checkedCities.includes('kuCun')" />
        <!--<el-table-column-->
        <!--label="添加时间"-->
        <!--min-width="120"-->
        <!--align="center"-->
        <!--v-if="checkedCities.includes('操作时间')"-->
        <!--&gt;-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{scope.row.addTime | formatDate}}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column
          label="商品状态"
          min-width="80"
          fixed="right"
          prop="productStatusDesc"
          v-if="checkedCities.includes('商品状态')"
        >
        </el-table-column>
        <el-table-column
          :label="$t('caoZuo')"
          min-width="180"
          fixed="right"
          align="center"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleAudit(scope.row.id, false)"
              v-hasPermi="['platform:product:info']"
              >{{ $t('xiangQing') }}</el-button
            >
            <el-button
              v-if="['2'].includes(tableFrom.type)"
              type="text"
              size="small"
              @click="handleAudit(scope.row.id, true)"
              v-hasPermi="['platform:product:audit']"
              >{{ $t('shenHe') }}</el-button
            >
            <el-button
              v-if="['2'].includes(tableFrom.type)"
              type="text"
              size="small"
              @click="handleSales(scope.row)"
              v-hasPermi="['platform:product:virtual:sales']"
              >{{ $t('xuNiXiaoLiang') }}</el-button
            >
            <el-button
              v-if="['7'].includes(tableFrom.type)"
              type="text"
              size="small"
              @click="handleOff(scope.row.id)"
              v-hasPermi="['platform:product:force:down']"
              >{{ $t('qiangZhiXiaJia') }}</el-button
            >
            <!-- <el-button
              type="text"
              size="small"
              @click="handleRestore(scope.row.id, scope.$index)"
              >{{ $t('huiFuShangPin') }}</el-button
            > -->
            <el-button
              v-if="['7'].includes(tableFrom.type)"
              type="text"
              size="small"
              @click="handleRank(scope.row)"
              v-hasPermi="['platform:product:update:rank']"
              >{{ $t('paiXu') }}</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="showBusinessFlow(scope.row.skuCode)"
              >业务流水</el-button>
            <!--<el-button type="text" size="small" @click="handleDelete(scope.row.id, tableFrom.type)" v-hasPermi="['admin:product:delete']">{{ tableFrom.type === '5' ? '删除' : '加入回收站' }}</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80,200]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <div class="card_abs" v-show="card_select_show">
      <template>
        <div class="cell_ht">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">{{
            $t('quanXuan')
          }}</el-checkbox>
          <el-button type="text" @click="checkSave()">{{ $t('baoCun') }}</el-button>
        </div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="item in columnData" :label="item" :key="item" class="check_cell">{{ $t(item) }}</el-checkbox>
        </el-checkbox-group>
      </template>
    </div>
    <el-dialog
      :title="$t('fuZhiTaoBaoTianMaoJingDongSuNing')"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1200px"
      class="taoBaoModal"
      :before-close="handleClose"
    >
      <tao-bao v-if="dialogVisible" @handleCloseMod="handleCloseMod"></tao-bao>
    </el-dialog>
    <info-from ref="infoFrom" :is-atud="isAtud" :is-show="isShow" :productId="productId" @subSuccess="subSuccess" />

    <batchReviewDialog ref="batchReviewRef" @subSuccess="getList"/>
    <!-- 业务流水 -->
    <businessFlow ref="businessFlowRef" />
  </div>
</template>

<script>
import {
  onChangeSalesApi,
  productLstApi,
  productDeleteApi,
  categoryApi,
  putOnShellApi,
  offShellApi,
  productHeadersApi,
  productExportApi,
  restoreApi,
  productExcelApi,
  updateRankApi,
  productAuditApi,
  exportExcelApi
} from '@/api/store';
import { getToken } from '@/utils/auth';
import taoBao from './taoBao';
import { checkPermi } from '@/utils/permission'; // 权限判断函数
import * as merchant from '@/api/merchant';
import infoFrom from './info';
import batchReviewDialog from './dialog/batchReview';
import { mapGetters } from 'vuex';

import businessFlow from '@/components/businessFlow';
export default {
  name: 'ProductList',
  directives: {
    // 计算是否滚动到最下面
    selectLoadMore: {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTWRAP_DOM.addEventListener('scroll', function () {
          if (this.scrollHeight - this.scrollTop < this.clientHeight + 1) {
            binding.value();
          }
        });
      },
    },
  },
  components: { taoBao, infoFrom, batchReviewDialog,businessFlow },
  data() {
    return {
      isAtud: false,
      isShow: false,
      productId: 0,
      categoryProps: {
        value: 'id',
        label: 'translateName',
        children: 'childList',
        expandTrigger: 'hover',
        checkStrictly: true,
        emitPath: false,
        multiple: false,
      },
      props: {
        children: 'child',
        label: 'name',
        value: 'id',
        emitPath: false,
      },
      isShowSeach: true,
      categoryIdData: [],
      // roterPre: roterPre,
      headeNum: [],
      listLoading: true,
      tableData: {
        data: [],
        total: 0,
      },
      tableFrom: {
        page: 1,
        limit: 20,
        categoryId: null,
        keywords: '',
        type: '1',
        isSelf: null,
      },
      categoryList: [],
      merCateList: [],
      objectUrl: process.env.VUE_APP_BASE_API,
      dialogVisible: false,
      card_select_show: false,
      checkAll: false,
      checkedCities: [
        'ID',
        'shangPinTuPian',
        'shangPinMingCheng',
        'shangPinFenLei',
        'shangPinShouJia',
        'shangHuMingCheng',
        'shangHuLeiBie',
        'xiaoLiang',
        'kuCun',
        '商品状态',
      ],
      columnData: [
        'ID',
        'shangPinTuPian',
        'shangPinMingCheng',
        'shangPinFenLei',
        'shangPinShouJia',
        'shangHuMingCheng',
        'shangHuLeiBie',
        'xiaoLiang',
        'kuCun',
        '商品状态',
      ],
      isIndeterminate: true,
      merchantList: [],
      search: {
        limit: 10,
        page: 1,
        keywords: '',
      },
      loading: false,
      totalPage: 0,
      total: 0,
      keyNum: 0,
      multipleSelection: [],
      OffId: [],
      headerName: [
        {
          name: this.$t('cangKuZhong'),
          type: 1,
          count:0
        },
        {
          name: this.$t('daiShenHe'),
          type: 2,
          count:0
        },
        {
          name: this.$t('shenHeShiBai'),
          type: 3,
          count:0
        },
        {
          name: this.$t('tongBuDaiShenHe'),
          type: 4,
          count:0
        },
        {
          name: this.$t('tongBuJuJue'),
          type: 5,
          count:0
        },
        {
          name: this.$t('tongBuYiShanChu'),
          type: 6,
          count:0
        },
        {
          name: this.$t('yiTongBu'),
          type: 7,
          count:0
        },
        {
          name: this.$t('tongBuWuKuCun'),
          type: 8,
          count:0
        },
      ],
      //  height: document.body.clientHeight
    };
  },
  computed: {
    ...mapGetters(['adminProductClassify','translateAdminProductClassifyArr']),
    heightBoxs: function () {
      this.$nextTick(() => {
        // 页面渲染完成后的回调
        return Number(this.$refs.headerBox.offsetHeight) - Number(document.documentElement.clientHeight);
      });
    },
  },
  async mounted() {

    if (!this.adminProductClassify.length) await this.$store.dispatch('product/getAdminProductClassify');
    this.getMerList();
    this.getList();
    this.checkedCities = this.$cache.local.has('goods_stroge')
      ? this.$cache.local.getJSON('goods_stroge')
      : this.checkedCities;
  },
  methods: {
    checkPermi,
    handleRank(editDate) {
      const _this = this;
      this.$modalParserFrom(
        this.$t('xiuGaiPaiXu'),
        160,
        1,
        { rank: editDate.adminSort, id: editDate.id },
        function (formValue) {
          _this.submitRank(formValue);
        },
        (this.keyNum += 5),
      );
    },
    submitRank(formValue) {
      const data = {
        id: formValue.id,
        rank: formValue.rank,
      };
      updateRankApi(data)
        .then((res) => {
          this.$message.success(this.$t('caoZuoChengGong'));
          this.$msgbox.close();
          this.getList();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 批量下架
    batchOff() {
      if (this.multipleSelection.length === 0) return this.$message.warning(this.$t('qingXianXuanZeShangPin'));
      this.handleOff(this.OffId);
    },
    // 下架
    handleOff(id) {
      this.$modalSure(this.$t('qiangZhiXiaJiaMa')).then(() => {
        this.listLoading = true
        offShellApi({
          ids: id.toString(),
        }).then((res) => {
          this.$message({
            type: 'success',
            message: this.$t('caoZuoChengGong'),
          });
          this.getList('');
          this.listLoading = false
        }).catch(()=>{
          this.listLoading = false
        });
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      const data = [];
      this.multipleSelection.map((item) => {
        data.push(item.id);
      });
      this.OffId = data;
    },
    handleSales(row) {
      const _this = this;
      this.$modalParserFrom(
        this.$t('xiuGaiXuNiXiaoLiang'),
        156,
        0,
        { ficti: row.ficti || '0', id: row.id },
        function (formValue) {
          _this.submit(formValue);
        },
        (this.keyNum += 5),
      );
    },
    submit(formValue) {
      const data = {
        id: formValue.id,
        num: formValue.num,
        type: formValue.type,
      };
      onChangeSalesApi(data)
        .then((res) => {
          this.$message.success(this.$t('caoZuoChengGong'));
          this.$msgbox.close();
          this.getList();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    subSuccess() {
      this.getList('');
    },
    handleAudit(id, c) {
      this.productId = id;
      this.$refs.infoFrom.dialogVisible = true;
      this.isShow = true;
      this.isAtud = c;
      this.$refs.infoFrom.getInfo(id);
    },
    // 下拉加载更多
    selectLoadMore() {
      this.search.page = this.search.page + 1;
      if (this.search.page > this.totalPage) return;
      this.getMerList(); // 请求接口
    },
    // 远程搜索
    remoteMethod(query) {
      this.loading = true;
      this.search.keywords = query;
      this.search.page = 1;
      this.merchantList = [];
      setTimeout(() => {
        this.loading = false;
        this.getMerList(); // 请求接口
      }, 200);
    },
    // 列表
    getMerList(num) {
      merchant
        .merchantListAddApi(this.search)
        .then((res) => {
          this.totalPage = res.totalPage;
          this.total = res.total;
          this.merchantList = this.merchantList.concat(res.list);
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    handleRestore(id) {
      this.$modalSure(this.$t('huiFuShangPin')).then(() => {
        restoreApi(id).then((res) => {
          this.$message.success(this.$t('caoZuoChengGong'));
          this.getList();
        });
      });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 导出
    exports() {
      productExcelApi({
        cateId: this.tableFrom.cateId,
        keywords: this.tableFrom.keywords,
        type: this.tableFrom.type,
      }).then((res) => {
        window.location.href = res.fileName;
      });
    },
    // 列表
    getList(num) {
      this.tableFrom.page = num ? num : this.tableFrom.page;
      this.listLoading = true;
      productLstApi(this.tableFrom)
        .then((res) => {
          for (let index = 0; index < this.headerName.length; index++) {
            for (let i = 0; i < res.tabsHeaderList.length; i++) {
              if(this.headerName[index].type === res.tabsHeaderList[i].type){
                this.headerName[index].count = res.tabsHeaderList[i].count
                break
              }
            }
          }

          this.tableData.data = res.pageInfo.list.map(item => {
            item.categoryName = this.getCategoryName(item.categoryId)
            return item
          })
          this.tableData.total = res.pageInfo.total;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    getCategoryName(categoryId) {
      const obj = this.translateAdminProductClassifyArr.find((e) => {
        return e.id == categoryId
      })
      return obj ? obj.translateName : ''
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList();
    },
    // 删除
    handleDelete(id, type) {
      this.$modalSure(this.$t('shanChuIdWeiIdDeShangPin', [id])).then(() => {
        const deleteFlag = type == 5 ? 'delete' : 'recycle';
        productDeleteApi(id, deleteFlag).then(() => {
          this.$message.success(this.$t('shanChuChengGong'));
          this.getList();
        });
      });
    },
    onchangeIsShow(row) {
      row.isShow
        ? putOnShellApi(row.id)
            .then(() => {
              this.$message.success(this.$t('shangJiaChengGong'));
              this.getList();
            })
            .catch(() => {
              row.isShow = !row.isShow;
            })
        : offShellApi(row.id)
            .then(() => {
              this.$message.success(this.$t('xiaJiaChengGong'));
              this.getList();
            })
            .catch(() => {
              row.isShow = !row.isShow;
            });
    },
    renderHeader(h) {
      return (
        <p>
          <span style="padding-right:5px;">{this.$t('caoZuo')}</span>
          <i class="el-icon-setting" onClick={() => this.handleAddItem()}></i>
        </p>
      );
    },
    handleAddItem() {
      if (this.card_select_show) {
        this.$set(this, 'card_select_show', false);
      } else if (!this.card_select_show) {
        this.$set(this, 'card_select_show', true);
      }
    },
    handleCloseMod(item) {
      this.dialogVisible = item;
      this.getList();
    },
    // 复制
    onCopy() {
      this.dialogVisible = true;
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.columnData : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.columnData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columnData.length;
    },
    checkSave() {
      this.$set(this, 'card_select_show', false);
      this.$modal.loading(this.$t('tishi14'));
      this.$cache.local.setJSON('goods_stroge', this.checkedCities);
      setTimeout(this.$modal.closeLoading(), 1000);
    },
    batchReview(){
      if(this.multipleSelection.length>0){
        this.$refs.batchReviewRef.show(this.multipleSelection)
      }else{
        this.$message.warning(this.$t('qingXuanZeXuYaoCaoZuoDeShuJu'));
      }

    },
    exportFn() {
      const productIdList = this.multipleSelection.map(it => it.id)
      exportExcelApi({ ...this.tableFrom, productIdList }).then(res => {
        const blob = new Blob([res.file], { type: 'application/octet-stream' })// res.data为文件流文件
        console.log(blob)
        this.$download.saveAs(blob, res.fileName)
      })
    },
    showBusinessFlow(id){
      this.$refs.businessFlowRef.show(id)
    }
  },
};
</script>

<style scoped lang="scss">
.el-table__body {
  width: 100%;
  table-layout: fixed !important;
}
.taoBaoModal {
  //  z-index: 3333 !important;
}
.demo-table-expand {
  ::v-deep label {
    width: 82px;
  }
}
.demo-table-expand {
  ::v-deep .el-form-item__content {
    width: 70%;
  }
}
.selWidth {
  width: 350px !important;
}
.seachTiele {
  line-height: 30px;
}
.relative {
  position: relative;
}
.card_abs {
  position: absolute;
  padding-bottom: 15px;
  top: 260px;
  right: 40px;
  width: 200px;
  background: #fff;
  z-index: 99999;
  box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.1);
}
.cell_ht {
  height: 50px;
  padding: 15px 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #eeeeee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.check_cell {
  width: 100%;
  padding: 15px 20px 0;
}
.mt-1 {
  margin-top: 6px;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #606266;
}
</style>
